/*zhaoyihang
 *登录验证
 * */
#include "threadPool.h"

int checkUser(int netfd,char *tmpBuf)
{
    while(1)
    {
        //接收用户名
        train_t train;
        char username[1024] = {0};
        int length;
        recvn(netfd,&length,sizeof(length));
        recvn(netfd,username,length); 
        printf("--------useruame:%s----------------\n",username);
        strcpy(tmpBuf,username);


        //检查名字是否重复
        char bufForCheckName[1024];
        snprintf(bufForCheckName, sizeof(bufForCheckName), "SELECT * FROM UserTable WHERE username='%s'", username);
        int qret = mysql_query(mysql,bufForCheckName);

        printf("返回的qret=%d\n",qret);
        //是否查到数据库
        if(qret !=0)
        {
            printf("Failed to execute query: %s\n", mysql_error(mysql));
            mysql_close(mysql);
            return 1;
        }
        // 查询成功，获取查询结果
        MYSQL_RES *result = mysql_store_result(mysql);
        if (result == NULL) {
            printf("Failed to get query result: %s\n", mysql_error(mysql));
            mysql_close(mysql);
            return 1;
        }
        // 检查查询结果
        int num_rows = mysql_num_rows(result);
        if (num_rows == 0) 
        {
            printf("客户输入了错误的用户名\n");
        }
        else
        {
            printf("准备登录！\n");
            //发送盐值
            bzero(&train,sizeof(train));
            train.length = strlen("ZLCXWY007");
            memcpy(train.data,"ZLCXWY007",strlen("ZLCXWY007"));
            send(netfd, &train, 4+train.length, MSG_WAITALL);
            //接受客户端的密文
            int buflen;
            char encryptedPass[4096];
            recv(netfd, &buflen, sizeof(int), MSG_WAITALL);
            recv(netfd, encryptedPass, buflen, MSG_WAITALL);
            
            //test
            printf("接收到客户端的密文：%s\n",encryptedPass);
            //获得数据库里存的密文
            MYSQL_ROW row;
            //test
            row = mysql_fetch_row(result);
           // while ((row = mysql_fetch_row(result)) != NULL)
           // {
           //     printf("%s\t%s\t%s\t%s\t%s\n", row[0], row[1], row[2],row[3],row[4]);
           // }
            //判断两个密文是否相同
            if(strcmp(encryptedPass,row[3])==0)
            {
                printf("登录成功\n");
                bzero(&train,sizeof(train));
                train.length = strlen("y"); 
                memcpy(train.data,"y",strlen("y"));
                send(netfd, &train, 4+train.length, MSG_WAITALL);

                //todo

            }
            else
            {
                printf("客户输入了错误的密码\n");
            }
            

        }
    
    }
}
